// 智谱AI API配置
const API_KEY = 'a4d51cc67d57476ea1e13111219dcc97.2bOoNCEufQf5wmZx';
const API_URL = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';

// 获取AI响应的函数
export const getAiResponse = (message) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: API_URL,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      data: {
        model: "glm-4-flash",
        messages: [
          {
            role: "user",
            content: message
          }
        ],
        temperature: 0.7,
        top_p: 0.95,
        max_tokens: 1000
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const data = res.data;
          // 检查API响应
          if (data.choices && data.choices[0] && data.choices[0].message) {
            resolve({
              success: true,
              data: data.choices[0].message.content,
              error: null
            });
          } else {
            reject(new Error('Invalid API response format'));
          }
        } else {
          reject(new Error(`HTTP error! status: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        console.error('调用AI接口出错:', err);
        reject(new Error(err.errMsg || '获取AI响应失败'));
      }
    });
  }).catch(error => {
    console.error('AI接口调用失败:', error);
    return {
      success: false,
      data: null,
      error: error.message || '获取AI响应失败'
    };
  });
};


